package at.dl.android.dota.adviser;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

public abstract class AbstractSearchActivity extends ActivityWithDB {

    public void onCreate ( Bundle savedInstanceState, 
                           final int layoutId, final int buttonId,
                           final Class lisrAtctivityClass, final String whereExtraName,
                           final String tableName, final String countFieldName ) {
        super.onCreate(savedInstanceState);
        setContentView(layoutId);

        Button searchButton = (Button) findViewById(buttonId);
        searchButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String where = mkWhere();
                String query = "SELECT COUNT(" + countFieldName + ") FROM " + tableName + where;
                SQLiteStatement statement = getDataBaseHelper().getReadableDatabase().compileStatement(query);
                long cnt = statement.simpleQueryForLong();
                if ( cnt > 0 && lisrAtctivityClass != null ) {
                    Intent myIntent = new Intent(view.getContext(), lisrAtctivityClass);
                    myIntent.putExtra(whereExtraName,where);
                    startActivity(myIntent);
                }
            }
        });
    }

    private String mkWhere () {
        ArrayList<String> whereElements = new ArrayList<String>();
        fillWhereElements(whereElements);
        
        String where = "";
        for ( int l = whereElements.size(), i = 0; i < l; i++ ) {
            if ( i == 0 )
                where = " WHERE ";
            else 
                where += " AND ";
            where += whereElements.get(i);
        }
        return where;
    }

    abstract protected void fillWhereElements ( List<String> whereElements );

    protected void addFromCheckBox ( List<String> whereElements, String dbField, int id ) {
        CheckBox cb = (CheckBox) findViewById(id);
        if ( cb.isChecked() )
            whereElements.add(dbField + " > 0");
    }

}
